package com.xxx.mybaitis;

import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

/**
 * sqlSession实现类
 */
public class DefaultSqlSession implements SqlSession {
	
	private Configuration configuration;

    private final Executor executor; // 具体执行sql的执行器
    
    public DefaultSqlSession(Configuration configuration) {
    	super();
    	this.configuration = configuration;
    	this.executor = new DefaultExecutor(configuration);
    }
    
    public Configuration getConfiguration() {
		return configuration;
	}

	/**
     * 通过jdk动态代理方式获取mapper接口的具体实例
     */
	@Override
	public <T> T getMapper(Class<T> type) {
		MappedProxy mappedProxy = new MappedProxy(this); 
		return (T)Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, mappedProxy);
	}

	@Override
	public <T> T selectOne(String statement, Object parameter) {
		List<T> list = this.selectList(statement, parameter);
        if (list == null || list.size() == 0) {
            return null;
        }
        if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("too man result");
        }
	}

	@Override
	public <E> List<E> selectList(String statement, Object parameter) {
		MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statement);
		return executor.query(mappedStatement, parameter);
	}

	@Override
	public int insert(String statement, Object parameter) throws SQLException {
		return update(statement, parameter);
	}

	@Override
	public int update(String statement, Object parameter) throws SQLException {
		MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statement);
		return executor.update(mappedStatement, parameter);
	}

	@Override
	public int delete(String statement, Object parameter) throws SQLException {
		return update(statement, parameter);
	}

}
